import React from 'react';

import styles from './index.module.less';

export default class Counter extends React.Component {
  state = {
    value: 1,
  };

  componentDidMount() {
    const { value } = this.props;

    this.setState({
      value,
    });
  }

  onCounterChange = e => {
    const value = e.target.value;

    this.setState((prevState, props) => {
      const { onChange = null } = props;

      typeof onChange === 'function' && onChange(value);

      return {
        value,
      };
    });
  };

  onCounterBtnClick = type => {
    this.setState((prevState, props) => {
      const {
        step = 1,
        max = null,
        min = 1,
      } = props;

      let { value } = prevState;

      if (type === 'minus') {
        if (value - step <= min) {
          value = min;
        } else {
          value -= step;
        }
      } else if (type === 'plus') {
        if (max !== null) {
          if (value + step >= max) {
            value = max;
          } else {
            value += step;
          }
        } else {
          value += step;
        }
      }

      return {
        value,
      };
    });
  };

  render() {
    const {
      max = null,
      min = 1,
    } = this.props;

    const { value } = this.state;

    return (
      <div className={styles.counterWrapper}>
        <button className={`${styles.counterBtn} ${value <= min ? styles.disabled : ''}`} disabled={value <= min} onClick={this.onCounterBtnClick.bind(this, 'minus')}>-</button>
        <input className={styles.counterInput} type='text' value={value} onChange={this.onCounterChange} />
        <button className={`${styles.counterBtn} ${value >= max ? styles.disabled : ''}`} disabled={value >= max} onClick={this.onCounterBtnClick.bind(this, 'plus')}>+</button>
      </div>
    );
  }
}
